﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace csharpcore7_ch14_ConcurrencyAndAsynchrony
{
    class chapt14_3_5TaskCompletionSource
    {
        static void _Main()
        {
            var tcs = new TaskCompletionSource<int>();
            new Thread(() =>
           {
               Thread.Sleep(5000);
               tcs.SetResult(42);
           })
           { IsBackground = true}.Start();

            Task<int> task = tcs.Task;      //Our's "slave" task.
            Console.WriteLine(task.Result); //42
        }

       
        static void __Main()
        {
            Task<Tresult> Run<Tresult>(Func<Tresult> function)
            {
                var tcs = new TaskCompletionSource<Tresult>();
                new Thread(() =>
                {
                    try { tcs.SetResult(function()); }
                    catch (Exception ex) { tcs.SetException(ex); }
                }
                    ).Start();
                return tcs.Task;
            }

            Task<int> task = Run(() => { Thread.Sleep(2000);return 42; });
           
            Task<string> task1 = Run(() => { Thread.Sleep(2000); return "hellowrold"; });
            Console.WriteLine(task.Result);
            Console.WriteLine(task1.Result);
        }

        static void ___Main()
        { 
            Task<int> GetAnswerToLife()
            {
                var tcs = new TaskCompletionSource<int>();
                //
                var timer = new System.Timers.Timer(5000) { AutoReset = false };
                timer.Elapsed += delegate { timer.Dispose(); tcs.SetResult(42); };
                timer.Start();
                return tcs.Task;
            }

            var awaiter = GetAnswerToLife().GetAwaiter();
            awaiter.OnCompleted(() => Console.WriteLine(awaiter.GetResult()));


            Console.Read();
        }

        //通用的Delay方法
        static Task Delay(int millisends)
        {
            var tcs = new TaskCompletionSource<object>();
            var timer = new System.Timers.Timer(millisends) { AutoReset = false };
            timer.Elapsed += delegate { timer.Dispose(); tcs.SetResult(null); };
            timer.Start();
            return tcs.Task;
        }
        static void ____Main()
        {           
            for(int i = 0;i< 10000;i++)
                Delay(5000).GetAwaiter().OnCompleted(() => Console.Write(42 + " "));

            Console.Read();
        }
    }
}
